package com.app.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.app.common.Result;
import com.app.mapper.ActivityMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.utils.CommonHelp;
import com.app.utils.TokenUtils;
import com.app.vo.ActivityVo;
import com.app.vo.BusinessDataVo;
import com.app.vo.BusinessVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 商家信息
 *
 * @author 16693103420
 * @since 2024-01-22
 */
@RestController
@RequestMapping("/business")
public class BusinessController {
    @Autowired
    private BusinessService businessService;
    @Autowired
    private FileService fileService;
    @Autowired
    private UserService userService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AdminUserService adminUserService;

    /**
     * 查询列表
     *
     * @param page
     * @param limit
     * @param keyword 商家名称
     * @param areaId  地区ID
     * @return
     */
    @GetMapping("/getBusinessList")
    public Result getBusinessList(@RequestParam(defaultValue = "0") Integer page,
                                  @RequestParam(defaultValue = "10") Integer limit,
                                  @RequestParam(required = false) String keyword,
                                  @RequestParam(required = false) Integer areaId,
                                  @RequestParam(required = false) Integer status,
                                  HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if ("false".equals(userId)) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        BusinessVo BusinessList = businessService.getBusinessList(user, page, limit, keyword, areaId, status);
        return Result.success(BusinessList);
    }

    //查询商家甄选活动
    @GetMapping("/getTranslateActivityList")
    public Result getTranslateActivityList(@RequestParam(defaultValue = "0") Integer page,
                                           @RequestParam(defaultValue = "10") Integer limit, Double longitude, Double latitude, String businessName, Integer areaId) {

        BusinessVo businessModelList = businessService.getTranslateActivityList(page, limit, longitude, latitude, businessName, areaId);
        return Result.success(businessModelList);
    }


    //查询商家甄选活动
    @GetMapping("/queryAndSelectMerchants")
    public Result queryAndSelectMerchants(@RequestParam(defaultValue = "1") Integer page,
                                          @RequestParam(defaultValue = "10") Integer limit,
                                          Double longitude,
                                          Double latitude,
                                          String businessName,
                                          Integer areaId,
                                          Integer sort,
                                          Integer type) {

        BusinessVo businessModelList = businessService.queryAndSelectMerchants(page, limit, longitude, latitude, businessName, areaId, sort, type);
        return Result.success(businessModelList);
    }

    //详情
    @GetMapping("/getBusinessById")
    public Result getBusinessById(Integer id) {
        BusinessModel business = businessService.getById(id);
        if (StrUtil.isNotBlank(business.getAreaCode())) {
            List<String> list = JSON.parseObject(business.getAreaCode(), new TypeReference<List<String>>() {
            });
            business.setValue(list);
        }
        List<FileModel> fileModelList = new ArrayList<>();
        if (StrUtil.isNotBlank(business.getFileId())) {
            String[] split = business.getFileId().split(",");
            for (String s : split) {
                FileModel fileModel = fileService.getById(s);
                fileModelList.add(fileModel);
            }
            business.setFile(fileModelList);
        }
        return Result.success(business);
    }


    /**
     * 商家列表  顶部的  甄选活动
     *
     * @param classification
     * @return
     */
    @GetMapping("/getIsPickActivityList")
    public Result getIsPickActivityList(Integer page,
                                        Integer limit,
                                        Integer classification,
                                        String activityName,
                                        Integer type,
                                        Integer sort,
                                        Double latitude,
                                        Double longitude) {
        ActivityVo vo = businessService.getIsPickActivityList(page, limit, classification, activityName, type, sort, latitude, longitude);
        return Result.success(vo);
    }

    /**
     * 用户查询商家列表
     *
     * @param page
     * @param limit
     * @param businessName 商家名称
     * @param areaId       地区ID
     * @param longitude    经度
     * @param latitude     纬度
     * @return
     */
    @GetMapping("/getUserBusinessList")
    public Result getUserBusinessList(@RequestParam(defaultValue = "0") Integer page,
                                      @RequestParam(defaultValue = "10") Integer limit,
                                      String businessName, String areaId, Integer type, Double longitude, Double latitude, Integer sort, Integer classification, HttpServletRequest request) {
        BusinessVo BusinessList = businessService.getUserBusinessList(page, limit, businessName, areaId, type, longitude, latitude, sort, classification, request);
        return Result.success(BusinessList);
    }

    @GetMapping("/getAllBusinessList")
    public Result getAllBusinessList(@RequestParam(defaultValue = "0") Integer page,
                                     @RequestParam(defaultValue = "10") Integer limit,
                                     String businessName, String areaId, Integer type, Double longitude, Double latitude, Integer sort, Integer classification, HttpServletRequest request) {
        BusinessVo BusinessList = businessService.getAllBusinessList(page, limit, businessName, areaId, type, longitude, latitude, sort, classification, request);
        return Result.success(BusinessList);
    }


    //商家经营数据
    @GetMapping("/getBusinessData")
    public Result getBusinessData(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel userModel = userService.getUserByOpenid(openId);
        if (userModel == null) {
            return Result.error(405, "用戶不存在");
        }
        Integer userId = userModel.getId();
        BusinessDataVo businessData = businessService.getBusinessData(userId);
        return Result.success(businessData);
    }


    /**
     * 用户查询商家详情
     *
     * @param id
     * @param longitude 经度
     * @param latitude  纬度
     * @return
     */
    @GetMapping("/getUserBusinessById")
    public Result getUserBusinessById(Integer id, Double longitude, Double latitude, HttpServletRequest request) {
        BusinessModel business = businessService.getUserById(id, longitude, latitude, request);
        if (business == null) {
            return Result.error(201, "商家不存在");
        }
        List<FileModel> fileModelList = new ArrayList<>();
        if (StrUtil.isNotBlank(business.getFileId())) {
            String[] split = business.getFileId().split(",");
            for (String s : split) {
                FileModel fileModel = fileService.getById(s);
                fileModelList.add(fileModel);
            }
            business.setFile(fileModelList);
        }
        return Result.success(business);
    }

    //新增和修改
    @PostMapping("/addAndUpdateBusiness")
    public Result addAndUpdateBusiness(@RequestBody BusinessModel businessModel) {
        if (StrUtil.isNotBlank(businessModel.getUserPhone())) {

            QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<>();
            userModelQueryWrapper.eq("phone", businessModel.getUserPhone());
            UserModel userModel = userService.getOne(userModelQueryWrapper);
            if (userModel == null) {
                return Result.error(201, "商家尚未注册平台,请填写正确的商家用户手机号");
            }
            userModel.setStatus(2);
            if (userModel.getVip() == 2) {
                userModel.setVip(1);
                if (StrUtil.isBlankIfStr(userModel.getInvitationCode())) {
                    this.userService.generateInvitationCode(userModel);
                }
            }
            if (businessModel.getValue() != null) {
                businessModel.setAreaCode(JSON.toJSONString(businessModel.getValue()));
                //同步商家定位为用户定位
                userModel.setCityId(businessModel.getCityId());
                userModel.setAreaId(businessModel.getAreaId());
                userModel.setAreaCode(JSON.toJSONString(businessModel.getValue()));
            }


            if (businessModel.getId() != null && businessModel.getId() > 0) {
                //判断是否是原来的手机号
                BusinessModel oldBusinessModel = this.businessService.getById(businessModel.getId());
                if (oldBusinessModel == null) {
                    return Result.error(200, "商家不存在");
                }
//                if (oldBusinessModel.getUserPhone() != null && businessModel.getUserPhone() != null) {
//                    //如果不一样,需要把原来的用户id更换掉
//                    if (!oldBusinessModel.getUserPhone().equals(businessModel.getUserPhone())) {
//                        QueryWrapper<UserModel> userModelQueryWrapper1 = new QueryWrapper<>();
//                        userModelQueryWrapper1.eq("phone", oldBusinessModel.getUserPhone());
//                        UserModel oldUserModel = userService.getOne(userModelQueryWrapper1);
//                        String
//                        oldUserModel.setPhone(userModel.getPhone());
//                        oldUserModel.setOpenId(userModel.getPhone());
//
//                    }
//                }
                businessModel.setUpdateTime(CommonHelp.getNowTimestamp());
                businessService.updateById(businessModel);
                userService.updateById(userModel);
                return Result.success("修改成功");
            } else {
                businessModel.setCreateTime(CommonHelp.getNowTimestamp());
                businessService.save(businessModel);
                userService.updateById(userModel);
                return Result.success("添加成功");
            }
        } else {
            return Result.error(201, "请填写正确的商家用户手机号");
        }
    }

    /**
     * 业务补助金
     *
     * @param id            id
     * @param voucherAmount 凭证金额
     * @param integral      积分
     * @param request       请求
     * @return {@link Result}<{@link Object}>
     */
    @GetMapping("/businessGrant")
    public Result<Object> businessGrant(Integer id, Double voucherAmount, Double integral, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        businessService.businessGrant(id, voucherAmount, integral);
        return Result.success("修改成功");
    }

    //删除
    @GetMapping("/delBusiness")
    public Result delBusiness(Integer id) {
        BusinessModel business = businessService.getById(id);
        if (business.getBusinessStatus() == 1) {
            return Result.error(201, "商家状态营业中，删除失败");
        }
        business.setStatus(2);
        businessService.updateById(business);
        List<ActivityModel> businessActivityList = activityMapper.getBusinessActivity(business.getId());
        if (!businessActivityList.isEmpty()) {
            for (ActivityModel model : businessActivityList) {
                model.setStatus(2);
            }
            activityService.updateBatchById(businessActivityList);
        }
        QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<>();
        userModelQueryWrapper.eq("phone", business.getUserPhone());
        UserModel userModel = userService.getOne(userModelQueryWrapper);
        if (userModel != null) {
            userModel.setStatus(1);
            userService.updateById(userModel);
        }
        return Result.success("删除成功");
    }

    /**
     * 获取类型列表
     *
     * @return {@link Result}
     */
    @GetMapping("/getTypeList")
    public Result getTypeList() {
        QueryWrapper<CategoryModel> categoryModelQueryWrapper = new QueryWrapper<>();
        categoryModelQueryWrapper.eq("pid", 10);
        List<CategoryModel> modelList = categoryService.list(categoryModelQueryWrapper);
        return Result.success(modelList);
    }

    /**
     * 获取商家选项
     *
     * @return {@link Result}
     */
    @GetMapping("/getMerchantOptions")
    public Result getMerchantOptions() {
        QueryWrapper<BusinessModel> businessModelQueryWrapper = new QueryWrapper<>();
        businessModelQueryWrapper.eq("business_status", 1);
        List<BusinessModel> modelList = businessService.list(businessModelQueryWrapper);
        return Result.success(modelList);
    }

    @GetMapping("/getMerchantOptionsList")
    public Result getMerchantOptionsList() {
        QueryWrapper<BusinessModel> businessModelQueryWrapper = new QueryWrapper<>();
        businessModelQueryWrapper.select("id", "business_name", "address");
        businessModelQueryWrapper.eq("business_status", 1);
        List<BusinessModel> modelList = businessService.list(businessModelQueryWrapper);
        return Result.success(modelList);
    }

    /**
     * 访问业务数据
     *
     * @return {@link Result}
     */
    @GetMapping("/accessToBusinessData")
    public Result accessToBusinessData(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel userModel = userService.getUserByOpenid(openId);
        if (userModel == null) {
            return Result.error(405, "用户不存在");
        }
        String dayDate = CommonHelp.getNowDate();
        String beginTimeDay = dayDate + " 00:00:00";
        String endTimeDay = dayDate + " 23:59:59";
        Map<String, Integer> map = this.businessService.accessToBusinessData(userModel.getId());
        try {
            QueryWrapper<BusinessModel> businessModelQueryWrapper = new QueryWrapper<>();
            businessModelQueryWrapper.eq("user_phone", userModel.getPhone());
            BusinessModel businessModel = this.businessService.getOne(businessModelQueryWrapper);
            if (businessModel != null) {
                Integer viewCount = activityService.getViewCount(businessModel.getId());
                map.put("viewCount", viewCount);
                QueryWrapper<OrderModel> orderModelQueryWrapper = new QueryWrapper<>();
                orderModelQueryWrapper.eq("business_id", businessModel.getId());
                map.put("orderCount", this.orderService.count(orderModelQueryWrapper));
//                map.put("todayCount", orderService.incomeTime(beginTimeDay, endTimeDay, businessModel.getId(), userModel.getId()).intValue());
                map.put("todayCount", orderService.getTodayMyVoucher(Integer.valueOf(userModel.getId())).intValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(map);
    }




    @GetMapping("/updateMobilePhoneInformationCorrespondingUserMerchant")
    public Result<Object> updateMobilePhoneInformationCorrespondingUserMerchant() {
        QueryWrapper<BusinessModel> businessModelQueryWrapper=new QueryWrapper<>();
        List<BusinessModel> businessModelList=this.businessService.list(businessModelQueryWrapper);
        for (BusinessModel business:businessModelList
             ) {
            QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<>();
            userModelQueryWrapper.eq("phone", business.getUserPhone());
            userModelQueryWrapper.eq("status", 2);
            userModelQueryWrapper.isNull("city_id");
            UserModel userModel = userService.getOne(userModelQueryWrapper);
            if(userModel==null)
            {
                continue;
            }
            userModel.setCityId(business.getCityId());
            userModel.setAreaId(business.getAreaId());
            userModel.setAreaCode(business.getAreaCode());
            this.userService.updateById(userModel);
        }
        return Result.success("修改成功");//修改成功
    }




}

